<?php
declare (strict_types = 1);

namespace app\admin\controller;
use think\facade\View;
use think\facade\Db;
class Admin extends \app\admin\controller\Base
{
  public function info()
  {
    $r = array();
    $r['avatar'] = 'https://i.gtimg.cn/club/item/face/img/2/15922_100.gif';
    $r['permissions'] = ['admin'];
    $r['username'] = $this->admin['name'];
    return $this->doSuccess('ok',$r);
  }

  public function insert()
  {
    $post = input('post.');
    $account = input('account');
    $mobile = input('mobile');
    $repassword = input('repassword');
    $name = input('name');
    if (!$account) {
      return $this->doError('登录帐号不能为空');
    }
    
    $pwLevel = checkPwLevel($repassword);
    if ($pwLevel ) {
      return $this->doError($pwLevel);
    }

    $ck = Db::name('admin')->where('account',$account)->find();
    if ($ck) {
      return $this->doError('登录帐号已存在');
    }
    $post['password'] = md5($repassword);
    $post['ctime'] = time();

    $ck = Db::name('admin')->insert($post);

    return $this->doSuccess('ok');
  }

  public function update()
  {
    $name = input('name');
    $repassword = input('repassword');
    $account = input('account');
    $id = input('id');
    $mobile = input('mobile');

    $post = array();
    $post['name'] = $name;
    $post['account'] = $account;
    $post['mobile'] = $mobile;
    if ($repassword) {
      $pwLevel = checkPwLevel($repassword);
      if ($pwLevel ) {
        return $this->doError($pwLevel);
      }
      $post['password'] = md5($repassword);
    }
    
    $ck = Db::name('admin')->where('id',$id)->update($post);
    return $this->doSuccess('ok');

  }
  //重置密码
  public function restpwd()
  {
    # code...
  }
  //修改密码
  public function changpwd()
  {

    $newpwd = input('newpwd');
    $oldpwd = input('oldpwd');
    $repwd = input('repwd');
    if ($newpwd != $repwd) {
      return $this->doError('两次输入新密码不一致');
    }

    $pwLevel = checkPwLevel($newpwd);
    if ($pwLevel ) {
      return $this->doError($pwLevel);
    }
    $ck = Db::name('admin')->where('id',$this->admin_id)->where('password',md5($oldpwd))->find();
    if (!$ck) {
      return $this->doError('旧密码错误');
    }
    if ($newpwd == $oldpwd) {
      return $this->doError('旧密码和新密码一致，无须更改');
    }

    Db::name('admin')->where('id',$this->admin_id)->update([
      'token'=>md5($newpwd).time(),
      'password'=>md5($newpwd)
    ]);
    return $this->doSuccess('密码修改成功，请使用新密码登录');

  }
  
}
